#include "stdafx.h"

bool g_FinishedCapturing = false;

//
// Callback for Ctrl+C routine.  Just sets global value that is used in wmain.
//
BOOL WINAPI CtrlCHandler(DWORD type)
{
	printf("*** CTRL+C ***\n");
	g_FinishedCapturing = true;

	return true;
}

int wmain(int argc, WCHAR* argv[])
{

	// Create object for interfacing with EventMon using Wbem.
	CEventMonWbem emw;

	// Class to handle Program Execution state.  Reads params,
	// sets up capture engine and parsers if needed.
	CPrgExeState pes(argc, argv);

	// Read the command line and validate the parameters.
	if(!pes.IsValidCommandLine())
	{
		pes.PrintHelp();
		return -1;
	}

	// If a m_Filter was specified, load the m_Filter and validate it's ok.
	if(pes.m_Filter != NULL){
		pes.LoadNPL();
		if(pes.IsNPLErrors())
		{
			wprintf(L"Error loading NPL.\n");
			return -1;
		}
	}


	HRESULT hRes;

	// Initalize the Wbem interface for reading the event logs.
	if(emw.Init())
	{
		// Open a capture file for saving frames, hard coded currently to largest size 100M
		if(!pes.CreateCap())
		{
			return -1;
		}


		// Configure the adapters to be ready to start capturing.
		if(!pes.InitCapture())
		{
			return -1;
		}

		// Make it so we can stop at any time.
		SetConsoleCtrlHandler(CtrlCHandler, true);

		// Now setup the query to look for our specific event error.
		if((hRes = emw.MonitorEvt(pes.m_EventNum, pes.m_LogFile)) == S_OK)
		{
			if(pes.m_LogFile == NULL)
			{
				wprintf(L"Capturing to %s until EventLog message %s\n", pes.m_CapFile, pes.m_EventNum);
			} else {
				wprintf(L"Capturing to %s until EventLog message %s from m_LogFile %s\n", pes.m_CapFile, pes.m_EventNum, pes.m_LogFile);
			}

			wprintf(L"Press Ctrl+C to exit early\n");

			// Start the capture and wait for the event to occur.  Poll every second so
			// we can capture a Ctrl+C if the user wants to exit early.
			if(pes.StartCapture()){
				ULONG uReturned = 0;

				while(uReturned == 0 && !g_FinishedCapturing)
				{
					if((hRes = emw.WaitForEvt(1000, &uReturned)) == WBEM_S_NO_ERROR)
					{
						wprintf(L"Received Event Log message.\n");
					} else if(hRes != WBEM_S_TIMEDOUT)
					{
						wprintf(L"Error getting event\n");
					}
				}

				wprintf(L"Stopping capture.  This may take a while if frames are pending...\n");

				pes.StopCapture();

				wprintf(L"Capture stopped\n");
			}
		} 
		else
		{
			wprintf(L"Unable to create Event Notification Query, 0x%X\n", hRes); 
		}
	}

    return 0;
}
